package com.zbkj.crmeb.order.channel;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.RestTemplateConfig;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.CarottaOrderRequest;
import com.zbkj.crmeb.order.request.CarottaOrderRequest.Address;
import com.zbkj.crmeb.order.request.CarottaOrderRequest.Customer;
import com.zbkj.crmeb.order.request.CarottaOrderRequest.Item;
import com.zbkj.crmeb.store.dao.PurchaseGoodsDao;
import com.zbkj.crmeb.store.dao.PurchaseOrderDao;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreOrderStatusService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class CarottaStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* carotta配置参数  *********/
    @Value("${carotta.url}")
    private String carottaUrl;
    @Value("${carotta.key}")
    private String carottaKey;
    @Value("${carotta.password}")
    private String carottaPassword;
    @Value("${carotta.version}")
    private String carottaVersion;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        try {
            storeOrder.setPushOrderNo(null);
            CarottaOrderRequest carottaOrderRequest = new CarottaOrderRequest();
            List<Item> items = new ArrayList<>();
            orderInfoVoList.forEach(order -> {
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                if(sourceSkuId.startsWith(ProductTypeEnum.CAROTTA.getCode()+"-")){
                    sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.CAROTTA.getCode()+"-","");
                }
                // 组建订单对象
                Item item = new Item();
                item.setVariantId(Long.parseLong(sourceSkuId)).setQuantity(order.getInfo().getCartNum());
                items.add(item);
            });
            carottaOrderRequest.setLineItems(items);
            carottaOrderRequest.setInventoryBehaviour("decrement_obeying_policy");
            carottaOrderRequest.setEmail("caigou@wzcprs.com");
            carottaOrderRequest.setShippingAddress(getShippingAddress());
            carottaOrderRequest.setBillingAddress(getBillingAddress());
            carottaOrderRequest.setCustomer(getCustomer());
            Result result = pushOrder(storeOrder, carottaOrderRequest, orderInfoVoList);
            if(!result.isSuccess()){
                return CommonResult.failed(result.getMessage());
            }
        } catch (Exception e) {
            log.info("--------------- 请求CAROTTA创建订单失败: {} ---------------", e.getMessage());
        }
        return CommonResult.success();
    }

    private Result pushOrder(StoreOrder storeOrder, CarottaOrderRequest req, List<StoreOrderInfoVo> orderInfoVoList) {
    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        StringBuilder sb = new StringBuilder().append("https://")
                .append(carottaKey)
                .append(":")
                .append(carottaPassword)
                .append("@")
                .append(carottaUrl)
                .append("/admin/api/")
                .append(carottaVersion)
                .append("/orders.json");
        log.info("--------------- 开始请求CAROTTA创建订单url: {} ---------------", sb);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject param = new JSONObject();
        param.put("order", JSONObject.toJSON(req));
        HttpEntity<JSONObject> formEntity = new HttpEntity<>(param, headers);
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        ResponseEntity<String> response = restTemplate.postForEntity(sb.toString(), formEntity, String.class);
        if (HttpStatus.CREATED != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");
            log.info("--------------- {} ---------------", errorMessage);
        }
        String channelOrdersn = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            JSONObject order = jsonObject.getJSONObject("order");
            channelOrdersn = order.get("id").toString();
        }catch (Exception e){
            log.error("--------请求CAROTTA创建订单返回结果转换异常:{}-----------",e.getMessage());
        }
        log.info("--------------- 请求CAROTTA创建订单返回结果: {} ---------------", response.toString());
        if(StringUtils.isNotBlank(channelOrdersn)){
            //新增采购单
            storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.CAROTTA.getCode());
            //新增采购商品
            storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, true, "CAROTTA推送: 成功", channelOrdersn, false);
    		StoreOrder storeOrderUpdate = new StoreOrder();
    		storeOrderUpdate.setId(storeOrder.getId());
    		storeOrderUpdate.setPushStatus(1);
    		storeOrderUpdate.setPushMessage("CAROTTA推送: 成功");
            storeOrderDao.updateById(storeOrderUpdate);
            return new Result(true, null, response.toString());
        }
        storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.CAROTTA.getCode());
        storeOrderFactory.insertPurchaseGoods(orderInfoVoList, storeOrder, false, "CAROTTA推送: 失败", channelOrdersn, false);
		StoreOrder storeOrderUpdate = new StoreOrder();
		storeOrderUpdate.setId(storeOrder.getId());
		storeOrderUpdate.setPushStatus(2);
		storeOrderUpdate.setPushMessage("CAROTTA推送:失败");
        storeOrderDao.updateById(storeOrderUpdate);
        return new Result(false, null, response.toString());
    }

    private Address getShippingAddress(){
        Address shippingAddress = new Address();
        shippingAddress.setFirstName("Mr");
        shippingAddress.setLastName("Joan");
        shippingAddress.setCountry("CN");
        shippingAddress.setProvince("HongKong");
        shippingAddress.setCity("HongKong");
        shippingAddress.setAddress1("Flat E, 7/F,Wing Shan Industrial Building, 0428 Cha Kwo Ling Road, Yau Tong, Kowloon, （YB001）");
        shippingAddress.setZip("999077");
        shippingAddress.setPhone("00852-97117670");
        return shippingAddress;
    }

    private Address getBillingAddress(){
        Address billingAddress = new Address();
        billingAddress.setFirstName("Mr");
        billingAddress.setLastName("Joan");
        billingAddress.setCountry("CN");
        billingAddress.setProvince("HongKong");
        billingAddress.setCity("HongKong");
        billingAddress.setAddress1("Flat E, 7/F,Wing Shan Industrial Building, 0428 Cha Kwo Ling Road, Yau Tong, Kowloon, （YB001）");
        billingAddress.setZip("999077");
        billingAddress.setPhone("00852-97117670");
//        billingAddress.setFirstName("La vita srl");
//        billingAddress.setLastName("La vita srl");
//        billingAddress.setCountry("IT");
//        billingAddress.setProvince("roma");
//        billingAddress.setCity("roma");
//        billingAddress.setAddress1("via emanuele filiberto 257,00185 roma");
//        billingAddress.setZip("00185");
//        billingAddress.setPhone("+393898858155");
        return billingAddress;
    }

    private Customer getCustomer(){
        Customer customer = new Customer();
        customer.setFirst_name("xun wu");
        customer.setLast_name("");
        customer.setEmail("caigou@wzcprs.com");
        return customer;
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }
}
